﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace IOA.MES.Client.Common.SocketUtils
{
    public class ByteUtils
    {
        /// <summary>
        /// 十六进制转字符串
        /// </summary>
        /// <param name="bytes">十六进制数组</param>
        /// <returns>字符串</returns>
        public static string HexToString(byte[] bytes)
        {
            string hexString = string.Empty;
            if (bytes != null)
            {
                var strList = new List<string>();
                for (int i = 0; i < bytes.Length; i++)
                {
                    strList.Add(bytes[i].ToString("X2"));
                }
                hexString = string.Join(" ", strList);
            }
            return hexString;
        }

        /// <summary>
        /// 十六进制转二进制
        /// </summary>
        /// <param name="bytes">十六进制数组</param>
        /// <returns>二进制数组</returns>
        public static byte[] HexToBit(byte[] bytes)
        {
            var bitStr = string.Empty;
            for (int i = 0; i < bytes.Length; i++)
            {
                bitStr = bitStr + Convert.ToString(bytes[i], 2).PadLeft(8, '0');
            }
            var result = new List<byte>();
            for (int i = 0; i < bitStr.Length; i++)
            {
                result.Add(Convert.ToByte(bitStr.Substring(i, 1)));
            }
            return result.ToArray();
        }

        /// <summary>
        /// 二进制转十进制
        /// </summary>
        /// <param name="bytes">二进制数组（1、0）</param>
        /// <returns>十进制</returns>
        public static int BitToInt(byte[] bytes)
        {
            var result = 0;
            for (int i = 0; i < bytes.Length; i++)
            {
                result = result + (int)(bytes[i] * Math.Pow(2, bytes.Length - i - 1));
            }
            return result;
        }

        /// <summary>
        /// 十六进制转十进制
        /// </summary>
        /// <param name="bytes">十六进制数组</param>
        /// <returns>十进制数</returns>
        public static long HexToDecimal(byte[] bytes)
        {
            var result = (long)0;
            var hexString = HexToString(bytes).Replace(" ", "").TrimStart('0');
            for (int i = 0; i < hexString.Length; i++)
            {
                result = result + (long)(Convert.ToInt32(hexString.Substring(i, 1), 16) * Math.Pow(16, hexString.Length - i - 1));
            }
            return result;
        }
    }
}
